<template>
  <div class="">
    <el-form :inline="true">
      <div style="display: flex; justify-content: space-between;">
        <div />
        <el-form-item>
          <el-button type="primary" @click="onVisible(1)">新增</el-button>
        </el-form-item>
      </div>
    </el-form>
    <el-table v-loading="listLoading" :data="tableData" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="60" align="center" />
      <el-table-column prop="rolename" label="角色名称" align="center" />
      <el-table-column prop="content" label="说明" align="center" />
      <el-table-column prop="valid" label="状态" width="100" align="center">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.valid" :disabled="scope.row.id == 1" :active-value="1" :inactive-value="0"
            @change="(val) => { return SetValid(val, scope.row) }" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="240px" align="center">
        <template v-if="scope.row.id != 1" slot-scope="scope">
          <el-button size="mini" type="primary" @click="onVisible(2, scope.row)">编辑</el-button>
          <!-- <el-button size="mini" type="danger" @click="onDelete(scope.row)">删除</el-button> -->
          <el-button size="mini" type="primary" @click="onSetAuth(scope.row)">分配权限</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination v-if="totalCount > 10" layout="prev, pager, next" :total="totalCount"
      @current-change="idx => { PageIndex = idx }" />
    <!-- 新增 -->
    <el-dialog :close-on-click-modal="false" :title="visibleType == '1' ? '新增权限' : '修改权限'" :visible.sync="dialogVisible"
      @closed="handleClose">
      <el-form ref="forms" :rules="rulesModel" :model="form" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" :rows="2" placeholder="请输入角色名称" />
        </el-form-item>
        <!-- 接口权限 -->
        <el-form-item label="说明" prop="content">
          <el-input v-model="form.url" :rows="2" placeholder="请输入说明" />
        </el-form-item>
        <el-form-item label="状态" prop="valid">
          <el-switch v-model="form.valid" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onEdit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限 -->
    <el-dialog :close-on-click-modal="false" title="分配权限" :visible.sync="AuthVisible" width="600px"
      @closed="$refs.tree.setCheckedKeys([]);">
      <el-tree ref="tree" :default-checked-keys="myAuth" :data="authList" :props="props" node-key="id" show-checkbox
        @node-click="handleNodeClick" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="AuthVisible = false">取 消</el-button>
        <el-button type="primary" @click="SetAuth">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { mapState } from 'vuex'
import {
  GetPage_Role,
  Delete_Role,
  AddEdit_Role,
  SetValid_SysUsers,
  GetPage_RoleAuth,
  Set_RoleAuth,
  GetPage_Auth
} from '@/api/sys.js'
export default {
  name: 'Name',
  data() {
    return {
      form: {},
      listLoading: false,
      tableData: [],
      totalCount: 0,
      PageIndex: 1,
      dialogVisible: false,

      AuthVisible: false,
      authList: [],
      myAuth: [], // 当前角色权限
      authModelMsg: {},
      props: {
        label: 'authname',
        children: 'children'
      },
      visibleType: '',
      rulesModel: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ]
      },
      parentIdArr: [], // 所有父级id
    }
  },
  computed: {},
  watch: {
    PageIndex(val) {
      this.getData()
    }
  },
  mounted() {
    this.getData()
    setTimeout(() => {
      this.getPid(-1);
      this.getPid(1);
    }, 500)
  },
  methods: {
    setFrom() {
      this.form = {
        id: 0,
        authName: '',
        valid: 1
      }
    },
    // 点击选择权限事件
    handleNodeClick(data) {
      console.log(data)
    },
    // 获取已选择
    async SetAuth() {
      // 不是全选  不返回父级id
      // const roleList = this.$refs.tree.getCheckedKeys()
      // 不是全选  返回父级id
      const roleList = this.$refs.tree.getCheckedKeys().concat(this.$refs.tree.getHalfCheckedKeys())
      console.log('选中的节点：', roleList)
      const { success, msg } = await Set_RoleAuth({
        roleid: this.authModelMsg.id
      }, roleList)
      if (success) {
        this.AuthVisible = false
      }
      this.$message({
        message: msg,
        type: success ? 'success' : 'error'
      })
    },
    // 打开分配角色
    async onSetAuth(val) {
      this.authModelMsg = val
      const { list } = await GetPage_RoleAuth({
        roleid: val.id,
        PageSize: 1000
      })
      const arr = []
      list.forEach(item => {
        // 只取子级id
        if (this.parentIdArr.indexOf(item.authid) == -1) {
          arr.push(item.authid)
        }
      })
      this.myAuth = [...new Set([...this.myAuth, ...arr])]
      console.log('已有权限ID', this.myAuth)
      this.AuthVisible = true
    },
    // 状态
    async SetValid(val, item) {
      const { success, msg } = await SetValid_SysUsers({
        id: item.id,
        valid: val
      })
      if (success) {
        this.getData()
      }
      this.$message({
        message: msg,
        type: success ? 'success' : 'error'
      })
    },
    // 获取权限列表
    async getPid(tag) {
      let parmar = {
        PageIndex: 1,
        PageSize: 10000
      }
      if (tag == 1) {
        parmar.tag = tag;
      }
      const { list } = await GetPage_Auth(parmar);
      if (tag == 1) {
        this.parentIdArr = list.map(item => { return item.id });
        // console.log('所有菜单id', this.parentIdArr);
      } else {
        this.authList = this.group(list, 0)
        // 禁用sys模块下的所有权限，并取出id
        let sysAuthList = [];
        this.authList.forEach(item => {
          if (item.acode == '/sys') {
            item.disabled = true
            sysAuthList.push(item.id)
            item.children.forEach(child => {
              child.disabled = true
              sysAuthList.push(child.id)
            })
          }
        })
        console.log('sysAuthList', sysAuthList)
        console.log('权限列表', this.authList)
        // 把sysAuthList数组中的元素添加到myAuth数组中，去重
        this.myAuth = [...new Set([...this.myAuth, ...sysAuthList])]
        console.log('myAuth', this.myAuth)
      }
    },
    // 分组筛选
    group(arr, parentId) {
      const tree = []
      arr.map((item) => {
        if (item.pid === parentId) {
          item.children = this.group(arr, item.id)
          tree.push(item)
        }
      })
      return tree
    },
    async onDelete(item) {
      try {
        const confirm = await this.$confirm('此操作将删除该配置, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        if (confirm == 'confirm') {
          const { success, msg } = await Delete_Role([item.id])
          this.getData()
          this.$message({
            message: msg,
            type: success ? 'success' : 'error'
          })
        }
      } catch (e) {
        // 取消
        console.log(e)
      }
    },
    onEdit() {
      this.$refs['forms'].validate(async (valid) => {
        if (valid) {
          this.form.tag = this.tag
          const { success, msg } = await AddEdit_Role(this.form)
          if (success) {
            this.dialogVisible = false
            this.getData()
          }
          this.$message({
            message: msg,
            type: success ? 'success' : 'error'
          })
        } else {
          return false
        }
      })
    },
    // 关闭前
    handleClose() {
      this.$refs.forms.resetFields()
      this.$refs.forms.clearValidate()
    },
    // 打开前
    onVisible(type, item = {}) {
      this.visibleType = type
      this.setFrom()
      this.form = { ...this.form, ...item }
      this.dialogVisible = true
    },
    async getData(address) {
      this.listLoading = true
      const { list, pageIndex, totalCount } = await GetPage_Role({
        PageIndex: this.PageIndex,
        PageSize: 10
      })
      this.totalCount = totalCount
      this.tableData = list
      this.listLoading = false
    }
  }
}
</script>

<style lang="scss" scoped></style>
<style lang="scss">
.el-table .warning-row {
  background: oldlace;
}
</style>
